package com.grf.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro配置类
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加Shiro内置过滤器

        //认证
        /*
            anon:无需认证
            authc:必须认证
            user:如果使用rememberMe的功能可以直接访问
            perms:拥有某个资源的权限才能访问
            role:拥有某个角色权限才能访问
         */
        Map filterMap = new LinkedHashMap<>();
        filterMap.put("/addUser", "authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //授权
        filterMap.put("/addUser","perms[user:add]");
        filterMap.put("/updateUser","perms[user:update]");

        //设置登录页面
        bean.setLoginUrl("/login");
        //设置未授权页面
        bean.setUnauthorizedUrl("/unauthorized");
        return bean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象，需要自定义
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }

}
